<?php
class CollectionController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to 'column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	//public $layout='column2';

	/**
	 * @var CActiveRecord the currently loaded data model instance.
	 */
	private $_model;

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
		array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view'),
				'users'=>array('*'),
		),
		array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update','ChooseCompany','ViewReport','getdetail','list'),
				'users'=>array('@'),
		),
		array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete'),
				'users'=>array('admin'),
		),
		array('deny',  // deny all users
				'users'=>array('*'),
		),
		);
	}

	/**
	 * Displays a particular model.
	 */
	public function actionViewReport(){
		$id = $_GET['id'];
		$type = $_GET['type'];
		$model = $this->loadModel();
		$admin = admin::model()->find('domain=:domain',array(':domain'=>Yii::app()->user->getState('provider')));
		if($type == 'html'){
			$this->renderPartial('reportHtml',array('model'=>$model,'admin'=>$admin));
		}
		else{
			$pdf = new tcpdf(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);;
			$html = $this->renderPartial('reportHtml',array('model'=>$model,'admin'=>$cname),true,true);
			$pdf->AddPage();
			$pdf->writeHTML($html, true, false, true, false, '');
			$pdf->Output('collection.pdf', 'I');
		}
	}
	public function actionGetDetail(){
		$model = $this->loadModel();
		$this->widget('zii.widgets.CDetailView', array(
    			'data'=>$model,
    			'attributes'=>array(
        			'req_date:date',             
        			'company',        
        			'consignee',  
					'complete_date:date',
					array(
						'label'=>'Packages',
						'value'=>CHtml::encode($model->pkg->qty.'/'.$model->pkg->wt.'/'.$model->pkg->m3),
					),
					array(
						'label'=>'Status',
						'value'=>'status',
					),
    			),
			));
	}
	public function actionView()
	{
		$model = $this->loadModel();
		if(Yii::app()->request->isAjaxRequest) {
			$this->widget('zii.widgets.CDetailView', array(
    			'data'=>$model,
    			'attributes'=>array(
        			'req_date:date',             
        			'company',        
        			'consignee',  
					'complete_date:date',
					array(
						'label'=>'Packages',
						'value'=>CHtml::encode($model->pkg->qty.'/'.$model->pkg->wt.'/'.$model->pkg->m3),
					),
					array(
						'label'=>'Status',
						'value'=>'status',
					),
    			),
			));
			Yii::app()->end();
		}
		$this->render('view',array(
			'model'=>$this->loadModel(),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionChooseCompany(){
		$model = new company('search');
		if(isset($_GET['company'])){
			$model->attributes = $_GET['company'];
		}
		echo $this->renderPartial('_gridCompany',array('model'=>$model),true, true);

	}
	private function checkCompany(){
		$company = new company;
		$id = 0;
		if($_POST['cargo_shipper']['id'] != 'undefined' && $_POST['cargo_shipper']['id'] != '0' && $_POST['cargo_shipper']['id'] != '')
		$id = $_POST['cargo_shipper']['id'];
		$company = company::model()->find('id=:id OR cname like :name',array(':id'=>$id,':name'=>$_POST['cargo_shipper']['cname']));
		if($company == null){
			$company->attributes = $_POST['cargo_shipper'];
			if(!$company->save())
			return false;
		}
		if(isset($_POST['company_address'])) {
			$address = company_address::model()->find('type=:type AND address=:address',array(':type'=>$_POST['company_address']['type'],':address'=>$_POST['collection']['address']));
			if($_POST['company_address']['id'] == '0' && $address == null){
				$address = new company_address;
				$address->company_id=$company->id;
				$address->address = $_POST['collection']['address'];
			}
			$address->attributes = $_POST['company_address'];
			if(!$address->save()){
				return false;
			}
		}
		if(isset($_POST['contacts'])){
			foreach($_POST['contacts'] as $contact){
				$contact = company_contacts::model()->find('type=:type AND ref=:ref',array(':type'=>$contact['type'],':ref'=>$contact['ref']));
				if($contact == null) {
					$member = company_members::model()->find('t.name=:name AND contacts.ref=:ref',array(':name'=>$contact['type'],':ref'=>$contact['ref']));
					if($member == null) {
						$member = array('name'=>$contact['type'],'type'=>'Direct line','company_id'=>$company->id);
						$company_member = new company_members;
						$company_member->attributes = $member;
						if($company_member->save()){
							$company_contact = new company_contacts;
							$company_contact->attributes = array('type'=>'Direct line','ref'=>$contact['ref']);
							$company_contact->member_id = $company_member->id;
							if($company_contact->save())
								return false;
						}
						else
							return false;
					}
				}
			}
		}
		return company;
	}
	public function actionCreate()
	{
		$model['collection'] = new collection;
		$model['detail'] = new collection_pkg;
		$model['collection']->cargo_id = $_GET['cargo_id'];
		if(!$model['collection']->validate(array('cargo_id')))
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
		$model['cargo'] = cargo::model()->findByPk($model['collection']->cargo_id);
		$model['collection']->company = $model['cargo']->shipper()->cname;
		$model['collection']->consignee = $model['cargo']->consignee()->cname;
		$model['detail']->qty = $model['cargo']->details->qty;
		$model['detail']->wt = $model['cargo']->details->wt;
		$model['detail']->m3 = $model['cargo']->details->m3;
		if(isset($_POST['collection'])) {
			$model['collection']->attributes=$_POST['collection'];
			$model['detail']->attributes=$_POST['collection_pkg'];
			$this->validateModels($model);
			$ajax = (isset($_POST['ajax']) && $_POST['ajax']==='collection-form' && Yii::app()->request->isAjaxRequest)?true:false;
			$transaction = Yii::app()->db->beginTransaction();
            try{
            	if(!$model['collection']->save())
            		throw new Exception("Saving error");            		
            	if(!$model['collection']->Add($model['detail'],'foreign_key'))
            		throw new Exception("Relation add error");
            	if(!jobs::model()->AddJob($model['collection'],'Collection'))
            		echo "job error";
            	$transaction->commit();
            	
            	if($ajax){
            		echo CJavaScript::jsonEncode(array('id'=>$model['collection']->id));
            		Yii::app()->end();
            	}
            	else
            		$this->redirect(array('/cargo/view','id'=>$model['collection']->cargo_id));
            }
            catch(Exception $e) {
            	$transaction->rollback();
            	if($ajax){
            		echo CJavaScript::jsonEncode(array('formerror'=>$e->getMessage()));
            		Yii::app()->end();
            	}
            }
		}
		if(Yii::app()->request->isAjaxRequest) {
			echo $this->renderPartial('create',array('model'=>$model),true,true);
			Yii::app()->end();
		}
		$this->render('create',array(
			'model'=>$model,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionUpdate()
	{
		$model=$this->loadModel();

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['collection']))
		{
			$model->attributes=$_POST['collection'];
			if($model->save())
			$this->redirect(array('view','id'=>$model->id));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'index' page.
	 */
	public function actionDelete()
	{
		if(Yii::app()->request->isPostRequest)
		{
			// we only allow deletion via POST request
			$this->loadModel()->delete();

			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if(!isset($_GET['ajax']))
			$this->redirect(array('index'));
		}
		else
		throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}

	/**
	 * Lists all models.
	 */
	public function actionList()
	{
		$dataProvider=new CActiveDataProvider('company');
		$this->render('list',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new collection('search');
		if(isset($_GET['collection']))
		$model->attributes=$_GET['collection'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 */
	public function loadModel()
	{
		if($this->_model===null)
		{
			if(isset($_GET['id']))
				$this->_model=collection::model()->findbyPk($_GET['id']);
			if($this->_model===null)
				if(Yii::app()->request->isAjaxRequest) {
					echo "No Collection";
					Yii::app()->end();
				}
				else
					throw new CHttpException(404,'The requested page does not exist.');
		}
		return $this->_model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='collection-form' && Yii::app()->request->isAjaxRequest)
		{
			if($model->validate())
				return;
			
			Yii::app()->end();
		}
	}
}
